package com.tueye.web.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.tueye.base.util.Page;
import com.tueye.entity.Adinfo;
import com.tueye.entity.Adsite;
import com.tueye.service.IAdinfoService;
import com.tueye.service.IAdsiteService;
import com.tueye.utils.DateUtils;
import com.tueye.utils.TuEyeConstant;
import com.tueye.utils.UUIDGenerator;

/**
 * 用户添加控制层操作demo
 * spring mvc 2.5 支持MultiActionController
 * @author hanxiaowei
 *
 */
@SuppressWarnings("unchecked")
@org.springframework.stereotype.Controller
@RequestMapping("/adinfo.do")
public class AdinfoController extends BaseController {
	private Log log = LogFactory.getLog(AdinfoController.class);
	
	@Autowired
	@Qualifier("adinfoService")
	private IAdinfoService adinfoService;
	@Autowired
	@Qualifier("adsiteService")
	private IAdsiteService adsiteService;
	@RequestMapping(params = "action=PageShow")
	public String PageShow (HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		// js传过来的参数列表：
		// page:页数
		// rp:每页显示多少条
		// sortname：排序的字段名称
		// sortorder: 排序的方向；比如：asc，desc；
		// query : 查询的条件
		// qtype ：查询的类型
		String id =request.getParameter("id");
		//System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"+id);
		if(id == null || id.length()==0){
			throw new NullPointerException();
		}
		String rp=request.getParameter("rp"); //每页显示的数据数
		String pageString=request.getParameter("page");//获取 flexgrid传过来的页数。
		String query=request.getParameter("query");//获取 查询的条件
		query = java.net.URLDecoder.decode(query , "UTF-8");//解码
		String error = request.getParameter("ss");
		//error.indexOf("23");
		String qtype=request.getParameter("qtype");//获取 查询的类型
		String sortorder=request.getParameter("sortorder");//获取 查询的类型
		if(pageString == null || pageString.length() == 0) {
			pageString = "1";
		}
		StringBuffer hql = new StringBuffer(" from com.tueye.entity.Adinfo ");
		//if(StringUtils.isNotEmpty(query)) hql.append(" where "+query);
		if(StringUtils.isNotEmpty(query)){ 
			hql.append(" where "+qtype+" ='"+query+"' and id = '"+id+"'");
		}else{
			hql.append(" where adsite_id = '"+id+"'");
		}
		if(StringUtils.isNotEmpty(qtype))hql.append("   order   by "+qtype);
		if(StringUtils.isNotEmpty(sortorder))hql.append("   "+sortorder);
		Page pageModel = adinfoService.pagedQueryByHQL(hql.toString(), Integer.valueOf(pageString), Integer.valueOf(rp), null);
		
		Map pageInfo = new HashMap();
		pageInfo.put("page", new Integer(pageString));
		pageInfo.put("total", pageModel.getTotalCount());
		//生成json字符串
		String jsonStr = getJsonString((ArrayList)pageModel.getResult(),pageInfo);
		response.setContentType("html/txt");
		response.setCharacterEncoding("utf-8");
		response.getWriter().println(jsonStr);
		
/*		response.setContentType("html/txt");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache, must-revalidate");
		response.setHeader("Pragma", "no-cache");
		response.getWriter().write(jsonStr);
		response.getWriter().flush();
		response.getWriter().close();*/
		
		return null;
	}
	
	@RequestMapping(params = "action=save")
	public String save(HttpServletRequest request, HttpServletResponse response) throws Exception {
	
	//	request.setCharacterEncoding("UTF-8");
		int adinfo_title_length = 0;
		int adinfo_description_length = 0;
		String adsite_id = (String) request.getParameter("adsite_id");
		String adinfo_title = (String)request.getParameter("adinfo_title");
		System.out.println(adinfo_title);
		String adinfo_description = request.getParameter("adinfo_description");
		int adinfo_level = Integer.parseInt(StringUtils.isEmpty(request.getParameter("adinfo_level"))?"0":request.getParameter("adinfo_level"));
		
		if(request.getParameter("adinfo_title_length")!= null && !"".equals(request.getParameter("adinfo_title_length"))){
			adinfo_title_length = Integer.parseInt(request.getParameter("adinfo_title_length"));//标题字节长度
		}
		if(request.getParameter("description_length") != null && !"".equals(request.getParameter("description_length"))){
			adinfo_description_length =Integer.parseInt(request.getParameter("description_length"));//描述显示长度	
		}
		String adinfo_address = request.getParameter("adinfo_address");  
		String adinfo_point_num = "0";
		String adpicture_site = null;
		//根据picture_site_type的值来判断图片的类型是什么，分为三种情况
		//1.本地图片 2.网络图片 3.没有图片
		String picture_site_type = request.getParameter("picture_site_type");
		if("2".equals(picture_site_type)){
		 adpicture_site = request.getParameter("adpicture_site");
		}else if("1".equals(picture_site_type)) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file  = multipartRequest.getFile("adpicture_site_local");
		String name = file.getOriginalFilename(); 
		if(name != null && !"".equals(name)){
		String newpath = TuEyeConstant.PROJECT_TOPIC_PATH +File.separatorChar+"aduploadimg"+File.separatorChar ; 
		file.transferTo(new File(newpath+name));
		adpicture_site = name;
		} 
		} 
		 
		//新增
		Adinfo adinfo = new Adinfo();
		adinfo.setId(new UUIDGenerator().getUUID());
		adinfo.setAdinfo_address(adinfo_address);
		adinfo.setAdinfo_title_length(adinfo_title_length);
		adinfo.setAdinfo_description_length(adinfo_description_length);
		adinfo.setAdinfo_description(adinfo_description);
		adinfo.setAdinfo_level(adinfo_level);
		adinfo.setAdinfo_point_num(adinfo_point_num);
		adinfo.setAdinfo_title(adinfo_title);
		adinfo.setAdpicture_site(adpicture_site);
		adinfo.setPicture_site_type(picture_site_type);
		Adsite adsite = adsiteService.getAdsiteById(adsite_id);
		adinfo.setAdsite(adsite);
		adinfo.setSys_time(new Date());
		adinfoService.addAdinfo(adinfo);
		request.setAttribute("adsite_id", adsite_id);
		return null;
	}
	
	@RequestMapping(params = "action=update")
	public String update(HttpServletRequest request, HttpServletResponse response) throws Exception {
	
		request.setCharacterEncoding("UTF-8");
		String mainId = (String) request.getParameter("id");
		String adsite_id = (String) request.getParameter("adsite_id");
		String adinfo_title = (String)request.getParameter("adinfo_title");
 		String adinfo_description = request.getParameter("adinfo_description");
		int adinfo_title_length =Integer.parseInt(request.getParameter("adinfo_title_length"));//标题字节长度
		int adinfo_description_length =Integer.parseInt( request.getParameter("adinfo_description_length"));//描述显示长度
		int adinfo_level = Integer.parseInt(request.getParameter("adinfo_level"));
		String adinfo_address = request.getParameter("adinfo_address");  
		String adinfo_point_num = request.getParameter("adinfo_point_num");  
		String adpicture_site = request.getParameter("adpicture_site");  
		//String picture_site_type = request.getParameter("picture_site_type");
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file  = multipartRequest.getFile("adpicture_site_local");
		String name = file.getOriginalFilename(); 
		
		//修改
		Adinfo adinfo = adinfoService.getAdinfoById(mainId);
		//adinfo.setId(mainId);
		adinfo.setAdinfo_address(adinfo_address);
 		adinfo.setAdinfo_description(adinfo_description);
		adinfo.setAdinfo_level(adinfo_level);
		adinfo.setAdinfo_point_num(adinfo_point_num);
		adinfo.setAdinfo_title(adinfo_title);
		adinfo.setAdinfo_description_length(adinfo_description_length);
		adinfo.setAdinfo_title_length(adinfo_title_length);
 		//adinfo.setPicture_site_type(picture_site_type);
		if(name == null || "".equals(name)){
		adinfo.setAdpicture_site(adpicture_site);
		}else{
			adpicture_site=null;
			String newpath = TuEyeConstant.PROJECT_TOPIC_PATH +File.separatorChar+"aduploadimg"+File.separatorChar ; 
			file.transferTo(new File(newpath+name));
			adpicture_site = name;
			adinfo.setAdpicture_site(adpicture_site);
		}
		
		Adsite adsite = adsiteService.getAdsiteById(adsite_id);
		adinfo.setAdsite(adsite);
		adinfo.setSys_time(new Date());
		adinfoService.addAdinfo(adinfo);
		request.setAttribute("adsite_id", adsite_id);
		return null;
	}
	/**
	 * @param list
	 * @param pageInfo
	 * @return
	 */
	@RequestMapping(params = "action=edit")
	public String edite(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		request.setCharacterEncoding("UTF-8");
		String mainId = (String) request.getParameter("id");
		String adsite_id = (String) request.getParameter("adsite_id");
		Adinfo adinfo = new Adinfo();
		//修改
	    adinfo = adinfoService.getAdinfoById(mainId);
	    request.setAttribute("adsite_id", adsite_id);
	    request.setAttribute("adinfo", adinfo);
	    return "/pages/admin/ad/updateAdinfo";
	}
	
	@RequestMapping(params = "action=delete")
	public String delete (HttpServletRequest request, HttpServletResponse response){
		
		String retult = "true";
		try {
			request.setCharacterEncoding("UTF-8");
			String id = request.getParameter("id");
			String mainId[]=id.split("\\,");
			for(int i=0;i <mainId.length;i++){ 
			
			//把id 弄成数组，for循环一一删掉
			Adinfo adinfo =  adinfoService.getAdinfoById(mainId[i]);
			String fn = adinfo.getAdpicture_site();
		
			delFiles(fn);
			adinfoService.delAdinfo(mainId[i]);
			//response.getWriter().print("true");
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("#####出错了"+e.getMessage());
			
		}
		return null;
	}
	
	private String getJsonString(List list, Map pageInfo) throws Exception{

		List mapList = new ArrayList();   
		for (int i = 0; i < list.size(); i++) {
			Adinfo adinfo = (Adinfo) list.get(i);
			if(adinfo.getPicture_site_type() != null){
			if(adinfo.getPicture_site_type().equals("1")){
			  adinfo.setPicture_site_type("本地上传图片");
			}else if(adinfo.getPicture_site_type().equals("2")){
				  adinfo.setPicture_site_type("网络图片");
			}else{
				adinfo.setPicture_site_type("无图片");
			}
			}else{adinfo.setPicture_site_type("无图片");} 
			Map cellMap = new HashMap();
			cellMap.put("numid", i+1);
    		cellMap.put("cell", new Object[]{
    				
    				adinfo.getId(),
    				i+1,
    				adinfo.getAdinfo_title(),
    				adinfo.getAdinfo_description(),
    				adinfo.getAdinfo_level(),
    				adinfo.getAdinfo_address(),
    				adinfo.getAdinfo_point_num(),
    				adinfo.getPicture_site_type(),
    				adinfo.getAdpicture_site(),
    				DateUtils.getDate2Str("yyyy-MM-dd HH:mm",adinfo.getSys_time())
    				});
    		  
    				mapList.add(cellMap);
    				
		}
		
    	pageInfo.put("rows", mapList);
    	com.tueye.ajax.json.JSONObject object = new com.tueye.ajax.json.JSONObject(pageInfo);
    	return object.toString();
	}
	/**
	 * 
	 * @param obj
	 * @return
	 */
	@SuppressWarnings("unused")
	private Object getJsonString(Object obj){
		
		JSONObject json = JSONObject.fromObject(obj);
		return json;
	}
	
	public boolean delFiles(String fn)  //fn为要删除的文件名，不包括路径 
	   { 
	   try 
	   { 
	   String newpath = TuEyeConstant.PROJECT_TOPIC_PATH +File.separatorChar+"aduploadimg"+File.separatorChar ; 
	   File file=new File(newpath+fn);  
	   if(file.exists()) 
	  { 
	     file.delete(); 
	 return true; 
	       }else 
	   { 
	 return true; 
	    } 
	   }catch(Exception e) 
	   { 
	   return false; 
	   } 
	   } 

}
